<!DOCTYPE html><html lang="en"><head><link rel="stylesheet" href="./style.css"><title>Utility - 30 seconds of code</title><meta charset="utf-8"><meta name="description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."><meta name="keywords" content="javascript, snippets, code, programming"><meta name="author" content="Angelos Chalaris (chalarangelo@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#111"><meta property="og:title" content="30 seconds of code"><meta property="og:description" content="Curated collection of useful Javascript snippets that you can understand in 30 seconds or less."/><meta property="og:type" content="website"/><meta property="og:image" content="https://30secondsofcode.org/logos/logo_512.png"><link rel="icon" type="image/png" href="./logos/logo_128.png"><link rel="manifest" href="manifest.json"><script>const search = (node) => {
        if(node.value.toLowerCase().trim() === ''){
          document.querySelector('nav').querySelectorAll('li').forEach(x => x.style.display = '');
          document.querySelector('nav').querySelectorAll('h4:not(.static-link)').forEach(x => x.classList = 'collapse');
          return;
        }
        let matchingTags = [];
        Array.from(document.querySelector('nav').querySelectorAll('li')).forEach(x => {
          let data = [x.textContent.toLowerCase(), ...x.querySelector('a').getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
          if(data.includes(true)){
            x.style.display = '';
            matchingTags.push(x.querySelector('a').getAttribute('tags').split(',')[0]);
          }
          else x.style.display = 'none';
        });
        Array.from(document.querySelector('nav').querySelectorAll('h4:not(.static-link)')).forEach(x => {
          x.classList = matchingTags.includes(x.textContent.toLowerCase()) ? 'collapse toggled' : 'collapse';
        })
      }
      function scrollToTop(){
        const c = document.querySelector('.card-container').scrollTop;
        if (c > 0) {
          window.requestAnimationFrame(scrollToTop);
          document.querySelector('.card-container').scrollTo(0, c - c / 4);
        }
      };
      function scrollTo(element, to, id, duration) {
        if (duration <= 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 40;

        setTimeout(function() {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) {
              window.location.href = "#"+id;
              return;
            }
            scrollTo(element, to, id, duration - 40);
        }, 40);
      };
      function loader() {
        if (window.location.href.split('#').length > 1)
          setTimeout(() => document.getElementById(window.location.href.split('#')[1]).scrollIntoView(), 0);
        registerClickListener();
        if(window.innerWidth >= '768')
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Utility')[0].offsetTop;
        else
          document.querySelector('nav').scrollTop = Array.from(document.querySelectorAll('h4')).filter(v => v.innerHTML === 'Utility')[0].offsetTop;
      }
      function registerClickListener() {
        document.addEventListener('click', function (event) {
          if ( event.target.classList.contains('collapse') ) {
            event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
          }
          else if (event.target.classList.contains('menu-button')) {
            document.querySelector('nav').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            document.querySelector('[type="search"]').classList = event.target.classList.contains('toggled') ? '' : 'col-nav';
            event.target.classList = event.target.classList.contains('toggled') ? 'menu-button' : 'menu-button toggled';
          }
          else if (!document.querySelector('nav').contains(event.target) && !document.querySelector('[type="search"]').contains(event.target) && window.innerWidth < '768') {
            document.querySelector('nav').classList = '';
            document.querySelector('[type="search"]').classList = '';
            document.querySelector('.menu-button').classList = 'menu-button';
          }
          else if (event.target.classList.contains('social')){
            if (event.target.classList.contains('fb')){
              window.location = "https://www.facebook.com/30secondsofcode";
            }
            else if (event.target.classList.contains('instagram')) {
              window.location = "https://www.instagram.com/30secondsofcode";
            }
            else if (event.target.classList.contains('twitter')) {
              window.location = "https://twitter.com/30secondsofcode";
            } 
          }
          else if (event.target.classList.contains('copy-button')) {
            const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
            const textArea = document.createElement("textarea");
            textArea.value = text.trim();
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand("Copy");
            document.body.removeChild(textArea);
            let tst = document.createElement('div');
            tst.classList = 'toast';
            tst.innerHTML = 'Snippet copied to clipboard!';
            document.body.appendChild(tst);
            setTimeout(function() {
              tst.style.opacity = 0;
              setTimeout(function() {
                document.body.removeChild(tst);
              },300);
            },1700);
          }
        }, false);
      }</script></head><body onload="loader()" class="card-page"><a href="https://github.com/30-seconds/30-seconds-of-code" class="github-corner" aria-label="View source on Github"><svg width="56" height="56" viewBox="0 0 250 250" style="fill:#009688;color:#fff;position:fixed;top:0;border:0;right:0;z-index:1000" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><button class="menu-button"></button><header><h1 class="logo"><a href="./index"><img src="https://30secondsofcode.org/logos/logo_256.png" alt="logo"/><span id="title">&nbsp;30 seconds of code</span> <small>Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.</small></a></h1></header><div class="container card-container"><input class="search" type="search" id="searchInput" onkeyup="search(this)" placeholder="Search..." aria-label="Snippet search"><nav><h4 class="collapse">Adapter</h4><ul><li><a tags="adapter,function,intermediate" href="./adapter#ary">ary</a></li><li><a tags="adapter,function,intermediate" href="./adapter#call">call</a></li><li><a tags="adapter,function,array,intermediate" href="./adapter#collectinto">collectInto</a></li><li><a tags="adapter,function,intermediate" href="./adapter#flip">flip</a></li><li><a tags="adapter,function,intermediate" href="./adapter#over">over</a></li><li><a tags="adapter,function,intermediate" href="./adapter#overargs">overArgs</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#pipeasyncfunctions">pipeAsyncFunctions</a></li><li><a tags="adapter,function,intermediate" href="./adapter#pipefunctions">pipeFunctions</a></li><li><a tags="adapter,function,promise,intermediate" href="./adapter#promisify">promisify</a></li><li><a tags="adapter,function,intermediate" href="./adapter#rearg">rearg</a></li><li><a tags="adapter,intermediate" href="./adapter#spreadover">spreadOver</a></li><li><a tags="adapter,function,intermediate" href="./adapter#unary">unary</a></li></ul><h4 class="collapse">Array</h4><ul><li><a tags="array,function,beginner" href="./index#all">all</a></li><li><a tags="array,function,beginner" href="./index#allequal">allEqual</a></li><li><a tags="array,function,beginner" href="./index#any">any</a></li><li><a tags="array,string,utility,intermediate" href="./index#arraytocsv">arrayToCSV</a></li><li><a tags="array,intermediate" href="./index#bifurcate">bifurcate</a></li><li><a tags="array,function,intermediate" href="./index#bifurcateby">bifurcateBy</a></li><li><a tags="array,intermediate" href="./index#chunk">chunk</a></li><li><a tags="array,beginner" href="./index#compact">compact</a></li><li><a tags="array,object,intermediate" href="./index#countby">countBy</a></li><li><a tags="array,intermediate" href="./index#countoccurrences">countOccurrences</a></li><li><a tags="array,recursion,intermediate" href="./index#deepflatten">deepFlatten</a></li><li><a tags="array,math,beginner" href="./index#difference">difference</a></li><li><a tags="array,function,intermediate" href="./index#differenceby">differenceBy</a></li><li><a tags="array,function,intermediate" href="./index#differencewith">differenceWith</a></li><li><a tags="array,beginner" href="./index#drop">drop</a></li><li><a tags="array,beginner" href="./index#dropright">dropRight</a></li><li><a tags="array,function,intermediate" href="./index#droprightwhile">dropRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#dropwhile">dropWhile</a></li><li><a tags="array,beginner" href="./index#everynth">everyNth</a></li><li><a tags="array,beginner" href="./index#filterfalsy">filterFalsy</a></li><li><a tags="array,beginner" href="./index#filternonunique">filterNonUnique</a></li><li><a tags="array,function,intermediate" href="./index#filternonuniqueby">filterNonUniqueBy</a></li><li><a tags="array,beginner" href="./index#findlast">findLast</a></li><li><a tags="array,function,intermediate" href="./index#findlastindex">findLastIndex</a></li><li><a tags="array,intermediate" href="./index#flatten">flatten</a></li><li><a tags="array,function,intermediate" href="./index#foreachright">forEachRight</a></li><li><a tags="array,object,intermediate" href="./index#groupby">groupBy</a></li><li><a tags="array,beginner" href="./index#head">head</a></li><li><a tags="array,intermediate" href="./index#indexofall">indexOfAll</a></li><li><a tags="array,beginner" href="./index#initial">initial</a></li><li><a tags="array,intermediate" href="./index#initialize2darray">initialize2DArray</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrange">initializeArrayWithRange</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithrangeright">initializeArrayWithRangeRight</a></li><li><a tags="array,math,intermediate" href="./index#initializearraywithvalues">initializeArrayWithValues</a></li><li><a tags="array,recursion,intermediate" href="./index#initializendarray">initializeNDArray</a></li><li><a tags="array,math,intermediate" href="./index#intersection">intersection</a></li><li><a tags="array,function,intermediate" href="./index#intersectionby">intersectionBy</a></li><li><a tags="array,function,intermediate" href="./index#intersectionwith">intersectionWith</a></li><li><a tags="array,intermediate" href="./index#issorted">isSorted</a></li><li><a tags="array,intermediate" href="./index#join">join</a></li><li><a tags="array,string,object,advanced" href="./index#jsontocsv">JSONtoCSV</a></li><li><a tags="array,beginner" href="./index#last">last</a></li><li><a tags="array,string,utility,intermediate" href="./index#longestitem">longestItem</a></li><li><a tags="array,object,advanced" href="./index#mapobject">mapObject</a></li><li><a tags="array,math,beginner" href="./index#maxn">maxN</a></li><li><a tags="array,math,beginner" href="./index#minn">minN</a></li><li><a tags="array,function,beginner" href="./index#none">none</a></li><li><a tags="array,beginner" href="./index#nthelement">nthElement</a></li><li><a tags="array,beginner" href="./index#offset">offset</a></li><li><a tags="array,object,function,intermediate" href="./index#partition">partition</a></li><li><a tags="array,recursion,advanced" href="./index#permutations">permutations</a></li><li><a tags="array,intermediate" href="./index#pull">pull</a></li><li><a tags="array,advanced" href="./index#pullatindex">pullAtIndex</a></li><li><a tags="array,advanced" href="./index#pullatvalue">pullAtValue</a></li><li><a tags="array,function,advanced" href="./index#pullby">pullBy</a></li><li><a tags="array,intermediate" href="./index#reducedfilter">reducedFilter</a></li><li><a tags="array,function,intermediate" href="./index#reducesuccessive">reduceSuccessive</a></li><li><a tags="array,function,intermediate" href="./index#reducewhich">reduceWhich</a></li><li><a tags="array,beginner" href="./index#reject">reject</a></li><li><a tags="array,intermediate" href="./index#remove">remove</a></li><li><a tags="array,random,beginner" href="./index#sample">sample</a></li><li><a tags="array,random,intermediate" href="./index#samplesize">sampleSize</a></li><li><a tags="array,intermediate" href="./index#shank">shank</a></li><li><a tags="array,random,intermediate" href="./index#shuffle">shuffle</a></li><li><a tags="array,math,beginner" href="./index#similarity">similarity</a></li><li><a tags="array,math,intermediate" href="./index#sortedindex">sortedIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedindexby">sortedIndexBy</a></li><li><a tags="array,math,intermediate" href="./index#sortedlastindex">sortedLastIndex</a></li><li><a tags="array,math,function,intermediate" href="./index#sortedlastindexby">sortedLastIndexBy</a></li><li><a tags="array,sort,advanced,intermediate" href="./index#stablesort">stableSort</a></li><li><a tags="array,math,intermediate" href="./index#symmetricdifference">symmetricDifference</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferenceby">symmetricDifferenceBy</a></li><li><a tags="array,function,intermediate" href="./index#symmetricdifferencewith">symmetricDifferenceWith</a></li><li><a tags="array,beginner" href="./index#tail">tail</a></li><li><a tags="array,beginner" href="./index#take">take</a></li><li><a tags="array,intermediate" href="./index#takeright">takeRight</a></li><li><a tags="array,function,intermediate" href="./index#takerightwhile">takeRightWhile</a></li><li><a tags="array,function,intermediate" href="./index#takewhile">takeWhile</a></li><li><a tags="array,intermediate" href="./index#tohash">toHash</a></li><li><a tags="array,math,beginner" href="./index#union">union</a></li><li><a tags="array,function,intermediate" href="./index#unionby">unionBy</a></li><li><a tags="array,function,intermediate" href="./index#unionwith">unionWith</a></li><li><a tags="array,beginner" href="./index#uniqueelements">uniqueElements</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsby">uniqueElementsBy</a></li><li><a tags="array,function,intermediate" href="./index#uniqueelementsbyright">uniqueElementsByRight</a></li><li><a tags="array,math,intermediate" href="./index#uniquesymmetricdifference">uniqueSymmetricDifference</a></li><li><a tags="array,intermediate" href="./index#unzip">unzip</a></li><li><a tags="array,function,advanced" href="./index#unzipwith">unzipWith</a></li><li><a tags="array,beginner" href="./index#without">without</a></li><li><a tags="array,math,intermediate" href="./index#xprod">xProd</a></li><li><a tags="array,intermediate" href="./index#zip">zip</a></li><li><a tags="array,object,intermediate" href="./index#zipobject">zipObject</a></li><li><a tags="array,function,advanced" href="./index#zipwith">zipWith</a></li></ul><h4 class="collapse">Browser</h4><ul><li><a tags="browser,array,intermediate" href="./browser#arraytohtmllist">arrayToHtmlList</a></li><li><a tags="browser,intermediate" href="./browser#bottomvisible">bottomVisible</a></li><li><a tags="browser,string,advanced" href="./browser#copytoclipboard">copyToClipboard</a></li><li><a tags="browser,advanced" href="./browser#counter">counter</a></li><li><a tags="browser,utility,beginner" href="./browser#createelement">createElement</a></li><li><a tags="browser,event,advanced" href="./browser#createeventhub">createEventHub</a></li><li><a tags="browser,url,beginner" href="./browser#currenturl">currentURL</a></li><li><a tags="browser,intermediate" href="./browser#detectdevicetype">detectDeviceType</a></li><li><a tags="browser,intermediate" href="./browser#elementcontains">elementContains</a></li><li><a tags="browser,advanced" href="./browser#elementisvisibleinviewport">elementIsVisibleInViewport</a></li><li><a tags="browser,object,intermediate" href="./browser#formtoobject">formToObject</a></li><li><a tags="browser,beginner" href="./browser#getimages">getImages</a></li><li><a tags="browser,intermediate" href="./browser#getscrollposition">getScrollPosition</a></li><li><a tags="browser,css,beginner" href="./browser#getstyle">getStyle</a></li><li><a tags="browser,css,beginner" href="./browser#hasclass">hasClass</a></li><li><a tags="browser,utility,advanced,promise,advanced" href="./browser#hashbrowser">hashBrowser</a></li><li><a tags="browser,css,beginner" href="./browser#hide">hide</a></li><li><a tags="browser,url,intermediate" href="./browser#httpsredirect">httpsRedirect</a></li><li><a tags="browser,beginner" href="./browser#insertafter">insertAfter</a></li><li><a tags="browser,beginner" href="./browser#insertbefore">insertBefore</a></li><li><a tags="browser,beginner" href="./browser#isbrowsertabfocused">isBrowserTabFocused</a></li><li><a tags="browser,array,beginner" href="./browser#nodelisttoarray">nodeListToArray</a></li><li><a tags="browser,event,advanced" href="./browser#observemutations">observeMutations</a></li><li><a tags="browser,event,intermediate" href="./browser#off">off</a></li><li><a tags="browser,event,intermediate" href="./browser#on">on</a></li><li><a tags="browser,event,advanced" href="./browser#onuserinputchange">onUserInputChange</a></li><li><a tags="browser,utility,intermediate" href="./browser#prefix">prefix</a></li><li><a tags="browser,utility,intermediate" href="./browser#recordanimationframes">recordAnimationFrames</a></li><li><a tags="browser,url,beginner" href="./browser#redirect">redirect</a></li><li><a tags="browser,function,advanced,promise,url" href="./browser#runasync">runAsync</a></li><li><a tags="browser,intermediate" href="./browser#scrolltotop">scrollToTop</a></li><li><a tags="browser,string,intermediate" href="./browser#serializeform">serializeForm</a></li><li><a tags="browser,beginner" href="./browser#setstyle">setStyle</a></li><li><a tags="browser,css,beginner" href="./browser#show">show</a></li><li><a tags="browser,css,intermediate" href="./browser#smoothscroll">smoothScroll</a></li><li><a tags="browser,beginner" href="./browser#toggleclass">toggleClass</a></li><li><a tags="browser,event,intermediate" href="./browser#triggerevent">triggerEvent</a></li><li><a tags="browser,utility,random,intermediate" href="./browser#uuidgeneratorbrowser">UUIDGeneratorBrowser</a></li></ul><h4 class="collapse">Date</h4><ul><li><a tags="date,beginner" href="./date#dayofyear">dayOfYear</a></li><li><a tags="date,math,string,utility,intermediate" href="./date#formatduration">formatDuration</a></li><li><a tags="date,intermediate" href="./date#getcolontimefromdate">getColonTimeFromDate</a></li><li><a tags="date,intermediate" href="./date#getdaysdiffbetweendates">getDaysDiffBetweenDates</a></li><li><a tags="date,beginner" href="./date#getmeridiemsuffixofinteger">getMeridiemSuffixOfInteger</a></li><li><a tags="date,utility,beginner" href="./date#isafterdate">isAfterDate</a></li><li><a tags="date,utility,beginner" href="./date#isbeforedate">isBeforeDate</a></li><li><a tags="date,utility,beginner" href="./date#issamedate">isSameDate</a></li><li><a tags="date,math,beginner" href="./date#maxdate">maxDate</a></li><li><a tags="date,math,beginner" href="./date#mindate">minDate</a></li><li><a tags="date,intermediate" href="./date#tomorrow">tomorrow</a></li></ul><h4 class="collapse">Function</h4><ul><li><a tags="function,intermediate" href="./function#attempt">attempt</a></li><li><a tags="function,object,intermediate" href="./function#bind">bind</a></li><li><a tags="function,object,intermediate" href="./function#bindkey">bindKey</a></li><li><a tags="function,intermediate" href="./function#chainasync">chainAsync</a></li><li><a tags="function,object,utility,beginner" href="./function#checkprop">checkProp</a></li><li><a tags="function,intermediate" href="./function#compose">compose</a></li><li><a tags="function,intermediate" href="./function#composeright">composeRight</a></li><li><a tags="function,intermediate" href="./function#converge">converge</a></li><li><a tags="function,recursion,intermediate" href="./function#curry">curry</a></li><li><a tags="function,intermediate" href="./function#debounce">debounce</a></li><li><a tags="function,intermediate" href="./function#defer">defer</a></li><li><a tags="function,intermediate" href="./function#delay">delay</a></li><li><a tags="function,utility,beginner" href="./function#functionname">functionName</a></li><li><a tags="function,intermediate" href="./function#hz">hz</a></li><li><a tags="function,advanced" href="./function#memoize">memoize</a></li><li><a tags="function,beginner" href="./function#negate">negate</a></li><li><a tags="function,intermediate" href="./function#once">once</a></li><li><a tags="function,intermediate" href="./function#partial">partial</a></li><li><a tags="function,intermediate" href="./function#partialright">partialRight</a></li><li><a tags="function,promise,intermediate" href="./function#runpromisesinseries">runPromisesInSeries</a></li><li><a tags="function,promise,intermediate" href="./function#sleep">sleep</a></li><li><a tags="function,advanced" href="./function#throttle">throttle</a></li><li><a tags="function,intermediate" href="./function#times">times</a></li><li><a tags="function,intermediate" href="./function#uncurry">uncurry</a></li><li><a tags="function,array,intermediate" href="./function#unfold">unfold</a></li><li><a tags="function,intermediate" href="./function#when">when</a></li></ul><h4 class="collapse">Math</h4><ul><li><a tags="math,beginner" href="./math#approximatelyequal">approximatelyEqual</a></li><li><a tags="math,array,beginner" href="./math#average">average</a></li><li><a tags="math,array,function,intermediate" href="./math#averageby">averageBy</a></li><li><a tags="math,intermediate" href="./math#binomialcoefficient">binomialCoefficient</a></li><li><a tags="math,beginner" href="./math#clampnumber">clampNumber</a></li><li><a tags="math,beginner" href="./math#degreestorads">degreesToRads</a></li><li><a tags="math,array,beginner" href="./math#digitize">digitize</a></li><li><a tags="math,beginner" href="./math#distance">distance</a></li><li><a tags="math,array,advanced" href="./math#elo">elo</a></li><li><a tags="math,recursion,beginner" href="./math#factorial">factorial</a></li><li><a tags="math,array,beginner" href="./math#fibonacci">fibonacci</a></li><li><a tags="math,recursion,beginner" href="./math#gcd">gcd</a></li><li><a tags="math,intermediate" href="./math#geometricprogression">geometricProgression</a></li><li><a tags="math,beginner" href="./math#hammingdistance">hammingDistance</a></li><li><a tags="math,beginner" href="./math#inrange">inRange</a></li><li><a tags="math,beginner" href="./math#isdivisible">isDivisible</a></li><li><a tags="math,beginner" href="./math#iseven">isEven</a></li><li><a tags="math,utility,beginner" href="./math#isnegativezero">isNegativeZero</a></li><li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li><li><a tags="math,recursion,beginner" href="./math#lcm">lcm</a></li><li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</a></li><li><a tags="math,beginner" href="./math#mapnumrange">mapNumRange</a></li><li><a tags="math,array,function,beginner" href="./math#maxby">maxBy</a></li><li><a tags="math,array,intermediate" href="./math#median">median</a></li><li><a tags="math,array,beginner" href="./math#midpoint">midpoint</a></li><li><a tags="math,array,function,beginner" href="./math#minby">minBy</a></li><li><a tags="math,intermediate" href="./math#percentile">percentile</a></li><li><a tags="math,beginner" href="./math#powerset">powerset</a></li><li><a tags="math,array,intermediate" href="./math#primes">primes</a></li><li><a tags="math,beginner" href="./math#radstodegrees">radsToDegrees</a></li><li><a tags="math,utility,random,intermediate" href="./math#randomintarrayinrange">randomIntArrayInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomintegerinrange">randomIntegerInRange</a></li><li><a tags="math,utility,random,beginner" href="./math#randomnumberinrange">randomNumberInRange</a></li><li><a tags="math,intermediate" href="./math#round">round</a></li><li><a tags="math,utility,intermediate" href="./math#sdbm">sdbm</a></li><li><a tags="math,array,intermediate" href="./math#standarddeviation">standardDeviation</a></li><li><a tags="math,array,beginner" href="./math#sum">sum</a></li><li><a tags="math,array,function,intermediate" href="./math#sumby">sumBy</a></li><li><a tags="math,intermediate" href="./math#sumpower">sumPower</a></li><li><a tags="math,beginner" href="./math#tosafeinteger">toSafeInteger</a></li><li><a tags="math,beginner" href="./math#vectordistance">vectorDistance</a></li></ul><h4 class="collapse">Node</h4><ul><li><a tags="node,string,utility,beginner" href="./node#atob">atob</a></li><li><a tags="node,string,utility,beginner" href="./node#btoa">btoa</a></li><li><a tags="node,utility,string,intermediate" href="./node#colorize">colorize</a></li><li><a tags="node,beginner" href="./node#createdirifnotexists">createDirIfNotExists</a></li><li><a tags="node,intermediate" href="./node#hasflags">hasFlags</a></li><li><a tags="node,utility,promise,intermediate" href="./node#hashnode">hashNode</a></li><li><a tags="node,type,intermediate" href="./node#isduplexstream">isDuplexStream</a></li><li><a tags="node,type,intermediate" href="./node#isreadablestream">isReadableStream</a></li><li><a tags="node,type,intermediate" href="./node#isstream">isStream</a></li><li><a tags="node,intermediate" href="./node#istravisci">isTravisCI</a></li><li><a tags="node,type,intermediate" href="./node#iswritablestream">isWritableStream</a></li><li><a tags="node,json,intermediate" href="./node#jsontofile">JSONToFile</a></li><li><a tags="node,array,string,beginner" href="./node#readfilelines">readFileLines</a></li><li><a tags="node,string,beginner" href="./node#untildify">untildify</a></li><li><a tags="node,utility,random,intermediate" href="./node#uuidgeneratornode">UUIDGeneratorNode</a></li></ul><h4 class="collapse">Object</h4><ul><li><a tags="object,function,intermediate" href="./object#bindall">bindAll</a></li><li><a tags="object,recursion,intermediate" href="./object#deepclone">deepClone</a></li><li><a tags="object,recursion,intermediate" href="./object#deepfreeze">deepFreeze</a></li><li><a tags="object,recursion,advanced" href="./object#deepmapkeys">deepMapKeys</a></li><li><a tags="object,intermediate" href="./object#defaults">defaults</a></li><li><a tags="object,recursion,intermediate" href="./object#dig">dig</a></li><li><a tags="object,array,type,advanced" href="./object#equals">equals</a></li><li><a tags="object,function,intermediate" href="./object#findkey">findKey</a></li><li><a tags="object,function,intermediate" href="./object#findlastkey">findLastKey</a></li><li><a tags="object,recursion,intermediate" href="./object#flattenobject">flattenObject</a></li><li><a tags="object,intermediate" href="./object#forown">forOwn</a></li><li><a tags="object,intermediate" href="./object#forownright">forOwnRight</a></li><li><a tags="object,function,intermediate" href="./object#functions">functions</a></li><li><a tags="object,intermediate" href="./object#get">get</a></li><li><a tags="object,function,intermediate" href="./object#invertkeyvalues">invertKeyValues</a></li><li><a tags="object,intermediate" href="./object#lowercasekeys">lowercaseKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapkeys">mapKeys</a></li><li><a tags="object,function,intermediate" href="./object#mapvalues">mapValues</a></li><li><a tags="object,type,intermediate" href="./object#matches">matches</a></li><li><a tags="object,type,function,intermediate" href="./object#matcheswith">matchesWith</a></li><li><a tags="object,array,intermediate" href="./object#merge">merge</a></li><li><a tags="object,intermediate" href="./object#nest">nest</a></li><li><a tags="object,array,beginner" href="./object#objectfrompairs">objectFromPairs</a></li><li><a tags="object,array,beginner" href="./object#objecttopairs">objectToPairs</a></li><li><a tags="object,array,intermediate" href="./object#omit">omit</a></li><li><a tags="object,array,function,intermediate" href="./object#omitby">omitBy</a></li><li><a tags="object,array,intermediate" href="./object#orderby">orderBy</a></li><li><a tags="object,array,intermediate" href="./object#pick">pick</a></li><li><a tags="object,array,function,intermediate" href="./object#pickby">pickBy</a></li><li><a tags="object,intermediate" href="./object#renamekeys">renameKeys</a></li><li><a tags="object,beginner" href="./object#shallowclone">shallowClone</a></li><li><a tags="object,array,string,intermediate" href="./object#size">size</a></li><li><a tags="object,array,intermediate" href="./object#transform">transform</a></li><li><a tags="object,logic,array,intermediate" href="./object#truthcheckcollection">truthCheckCollection</a></li><li><a tags="object,advanced" href="./object#unflattenobject">unflattenObject</a></li></ul><h4 class="collapse">String</h4><ul><li><a tags="string,beginner" href="./string#bytesize">byteSize</a></li><li><a tags="string,array,intermediate" href="./string#capitalize">capitalize</a></li><li><a tags="string,regexp,intermediate" href="./string#capitalizeeveryword">capitalizeEveryWord</a></li><li><a tags="string,regexp,beginner" href="./string#compactwhitespace">compactWhitespace</a></li><li><a tags="string,array,utility,intermediate" href="./string#csvtoarray">CSVToArray</a></li><li><a tags="string,array,object,advanced" href="./string#csvtojson">CSVToJSON</a></li><li><a tags="string,array,intermediate" href="./string#decapitalize">decapitalize</a></li><li><a tags="string,browser,regexp,intermediate" href="./string#escapehtml">escapeHTML</a></li><li><a tags="string,regexp,intermediate" href="./string#escaperegexp">escapeRegExp</a></li><li><a tags="string,intermediate" href="./string#fromcamelcase">fromCamelCase</a></li><li><a tags="string,utility,beginner" href="./string#indentstring">indentString</a></li><li><a tags="string,utility,browser,url,intermediate" href="./string#isabsoluteurl">isAbsoluteURL</a></li><li><a tags="string,regexp,intermediate" href="./string#isanagram">isAnagram</a></li><li><a tags="string,utility,beginner" href="./string#islowercase">isLowerCase</a></li><li><a tags="string,utility,beginner" href="./string#isuppercase">isUpperCase</a></li><li><a tags="string,array,function,utility,beginner" href="./string#mapstring">mapString</a></li><li><a tags="string,utility,regexp,intermediate" href="./string#mask">mask</a></li><li><a tags="string,beginner" href="./string#pad">pad</a></li><li><a tags="string,intermediate" href="./string#palindrome">palindrome</a></li><li><a tags="string,intermediate" href="./string#pluralize">pluralize</a></li><li><a tags="string,regexp,intermediate" href="./string#removenonascii">removeNonASCII</a></li><li><a tags="string,array,beginner" href="./string#reversestring">reverseString</a></li><li><a tags="string,beginner" href="./string#sortcharactersinstring">sortCharactersInString</a></li><li><a tags="string,beginner" href="./string#splitlines">splitLines</a></li><li><a tags="string,recursion,advanced" href="./string#stringpermutations">stringPermutations</a></li><li><a tags="string,utility,regexp,beginner" href="./string#striphtmltags">stripHTMLTags</a></li><li><a tags="string,regexp,intermediate" href="./string#tocamelcase">toCamelCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tokebabcase">toKebabCase</a></li><li><a tags="string,regexp,intermediate" href="./string#tosnakecase">toSnakeCase</a></li><li><a tags="string,regepx,intermediate" href="./string#totitlecase">toTitleCase</a></li><li><a tags="string,beginner" href="./string#truncatestring">truncateString</a></li><li><a tags="string,browser,beginner" href="./string#unescapehtml">unescapeHTML</a></li><li><a tags="string,utility,regexp,advanced" href="./string#urljoin">URLJoin</a></li><li><a tags="string,regexp,intermediate" href="./string#words">words</a></li></ul><h4 class="collapse">Type</h4><ul><li><a tags="type,beginner" href="./type#gettype">getType</a></li><li><a tags="type,array,regexp,beginner" href="./type#is">is</a></li><li><a tags="type,array,intermediate" href="./type#isarraylike">isArrayLike</a></li><li><a tags="type,beginner" href="./type#isboolean">isBoolean</a></li><li><a tags="type,array,object,string,beginner" href="./type#isempty">isEmpty</a></li><li><a tags="type,function,beginner" href="./type#isfunction">isFunction</a></li><li><a tags="type,beginner" href="./type#isnil">isNil</a></li><li><a tags="type,beginner" href="./type#isnull">isNull</a></li><li><a tags="type,math,beginner" href="./type#isnumber">isNumber</a></li><li><a tags="type,object,beginner" href="./type#isobject">isObject</a></li><li><a tags="type,object,beginner" href="./type#isobjectlike">isObjectLike</a></li><li><a tags="type,object,intermediate" href="./type#isplainobject">isPlainObject</a></li><li><a tags="type,function,array,string,intermediate" href="./type#isprimitive">isPrimitive</a></li><li><a tags="type,function,promise,intermediate" href="./type#ispromiselike">isPromiseLike</a></li><li><a tags="type,string,beginner" href="./type#isstring">isString</a></li><li><a tags="type,beginner" href="./type#issymbol">isSymbol</a></li><li><a tags="type,beginner" href="./type#isundefined">isUndefined</a></li><li><a tags="type,json,intermediate" href="./type#isvalidjson">isValidJSON</a></li></ul><h4 class="collapse">Utility</h4><ul><li><a tags="utility,array,type,beginner" href="#castarray">castArray</a></li><li><a tags="utility,regexp,intermediate" href="#cloneregexp">cloneRegExp</a></li><li><a tags="utility,beginner" href="#coalesce">coalesce</a></li><li><a tags="utility,intermediate" href="#coalescefactory">coalesceFactory</a></li><li><a tags="utility,string,intermediate" href="#extendhex">extendHex</a></li><li><a tags="utility,browser,string,url,intermediate" href="#geturlparameters">getURLParameters</a></li><li><a tags="utility,string,math,advanced" href="#hextorgb">hexToRGB</a></li><li><a tags="utility,url,browser,intermediate" href="#httpget">httpGet</a></li><li><a tags="utility,url,browser,intermediate" href="#httppost">httpPost</a></li><li><a tags="utility,browser,intermediate" href="#isbrowser">isBrowser</a></li><li><a tags="utility,function" href="#mostperformant">mostPerformant</a></li><li><a tags="utility,function,beginner" href="#ntharg">nthArg</a></li><li><a tags="utility,string,intermediate" href="#parsecookie">parseCookie</a></li><li><a tags="utility,string,math,advanced" href="#prettybytes">prettyBytes</a></li><li><a tags="utility,random,beginner" href="#randomhexcolorcode">randomHexColorCode</a></li><li><a tags="utility,intermediate" href="#rgbtohex">RGBToHex</a></li><li><a tags="utility,string,intermediate" href="#serializecookie">serializeCookie</a></li><li><a tags="utility,beginner" href="#timetaken">timeTaken</a></li><li><a tags="utility,intermediate" href="#tocurrency">toCurrency</a></li><li><a tags="utility,math,beginner" href="#todecimalmark">toDecimalMark</a></li><li><a tags="utility,math,intermediate" href="#toordinalsuffix">toOrdinalSuffix</a></li><li><a tags="utility,math,intermediate" href="#validatenumber">validateNumber</a></li><li><a tags="utility,regexp,intermediate" href="#yesno">yesNo</a></li></ul><h4 class="static-link"><a href="./archive">Archive</a></h4><h4 class="static-link"><a href="./glossary">Glossary</a></h4><h4 class="static-link"><a href="./contributing">Contributing</a></h4><h4 class="static-link"><a href="./about">About</a></h4><div><button class="social fb"></button><button class="social instagram"></button><button class="social twitter"></button></div></nav><main class="col-centered"><span id="top"><br/><br/></span><h2 class="category-name">Utility</h2><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="castarray">castArray</h4><p>Casts the provided value as an array if it's not one.</p><p>Use <code>Array.prototype.isArray()</code> to determine if <code>val</code> is an array and return it as-is or encapsulated in an array accordingly.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">castArray</span> <span class="token operator">=</span> val <span class="token operator">=></span> <span class="token punctuation">(</span>Array<span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">?</span> val <span class="token punctuation">: [</span>val<span class="token punctuation">]);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">castArray</span><span class="token punctuation">(</span><span class="token string">'foo'</span><span class="token punctuation">);</span> <span class="token comment">// ['foo']</span>
<span class="token function">castArray</span><span class="token punctuation">([</span><span class="token number">1</span><span class="token punctuation">]);</span> <span class="token comment">// [1]</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="cloneregexp">cloneRegExp</h4><p>Clones a regular expression.</p><p>Use <code>new RegExp()</code>, <code>RegExp.source</code> and <code>RegExp.flags</code> to clone the given regular expression.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">cloneRegExp</span> <span class="token operator">=</span> regExp <span class="token operator">=></span> <span class="token keyword">new</span> <span class="token class-name">RegExp</span><span class="token punctuation">(</span>regExp<span class="token punctuation">.</span>source<span class="token punctuation">,</span> regExp<span class="token punctuation">.</span>flags<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> regExp <span class="token operator">=</span> <span class="token regex">/lorem ipsum/gi</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> regExp2 <span class="token operator">=</span> <span class="token function">cloneRegExp</span><span class="token punctuation">(</span>regExp<span class="token punctuation">);</span> <span class="token comment">// /lorem ipsum/gi</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="coalesce">coalesce</h4><p>Returns the first non-null/undefined argument.</p><p>Use <code>Array.prototype.find()</code> to return the first non <code>null</code>/<code>undefined</code> argument.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">coalesce</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> args<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span>_ <span class="token operator">=> !</span><span class="token punctuation">[</span>undefined<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">].</span><span class="token function">includes</span><span class="token punctuation">(</span>_<span class="token punctuation">));</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">coalesce</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> undefined<span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">,</span> <span class="token number">NaN</span><span class="token punctuation">,</span> <span class="token string">'Waldo'</span><span class="token punctuation">);</span> <span class="token comment">// ""</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="coalescefactory">coalesceFactory</h4><p>Returns a customized coalesce function that returns the first argument that returns <code>true</code> from the provided argument validation function.</p><p>Use <code>Array.prototype.find()</code> to return the first argument that returns <code>true</code> from the provided argument validation function.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">coalesceFactory</span> <span class="token operator">=</span> valid <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> args<span class="token punctuation">.</span><span class="token function">find</span><span class="token punctuation">(</span>valid<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> customCoalesce <span class="token operator">=</span> <span class="token function">coalesceFactory</span><span class="token punctuation">(</span>_ <span class="token operator">=> !</span><span class="token punctuation">[</span><span class="token keyword">null</span><span class="token punctuation">,</span> undefined<span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">,</span> <span class="token number">NaN</span><span class="token punctuation">].</span><span class="token function">includes</span><span class="token punctuation">(</span>_<span class="token punctuation">));</span>
<span class="token function">customCoalesce</span><span class="token punctuation">(</span>undefined<span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token number">NaN</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">,</span> <span class="token string">'Waldo'</span><span class="token punctuation">);</span> <span class="token comment">// "Waldo"</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="extendhex">extendHex</h4><p>Extends a 3-digit color code to a 6-digit color code.</p><p>Use <code>Array.prototype.map()</code>, <code>String.prototype.split()</code> and <code>Array.prototype.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. <code>Array.prototype.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">extendHex</span> <span class="token operator">=</span> shortHex <span class="token operator">=></span>
  <span class="token string">'#'</span> <span class="token operator">+</span>
  shortHex
    <span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span>shortHex<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">'#'</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token number">1</span> <span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">)
    .</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">)
    .</span><span class="token function">map</span><span class="token punctuation">(</span>x <span class="token operator">=></span> x <span class="token operator">+</span> x<span class="token punctuation">)
    .</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">extendHex</span><span class="token punctuation">(</span><span class="token string">'#03f'</span><span class="token punctuation">);</span> <span class="token comment">// '#0033ff'</span>
<span class="token function">extendHex</span><span class="token punctuation">(</span><span class="token string">'05a'</span><span class="token punctuation">);</span> <span class="token comment">// '#0055aa'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="geturlparameters">getURLParameters</h4><p>Returns an object containing the parameters of the current URL.</p><p>Use <code>String.match()</code> with an appropriate regular expression to get all key-value pairs, <code>Array.prototype.reduce()</code> to map and combine them into a single object. Pass <code>location.search</code> as the argument to apply to the current <code>url</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">getURLParameters</span> <span class="token operator">=</span> url <span class="token operator">=></span>
  <span class="token punctuation">(</span>url<span class="token punctuation">.</span><span class="token function">match</span><span class="token punctuation">(</span><span class="token regex">/([^?=&amp;]+)(=([^&amp;]*))/g</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">[]).</span><span class="token function">reduce</span><span class="token punctuation">(
    (</span>a<span class="token punctuation">,</span> v<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">((</span>a<span class="token punctuation">[</span>v<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> v<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string">'='</span><span class="token punctuation">))]</span> <span class="token operator">=</span> v<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span>v<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string">'='</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)),</span> a<span class="token punctuation">),
    {}
  );</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">getURLParameters</span><span class="token punctuation">(</span><span class="token string">'http://url.com/page?name=Adam&amp;surname=Smith'</span><span class="token punctuation">);</span> <span class="token comment">// {name: 'Adam', surname: 'Smith'}</span>
<span class="token function">getURLParameters</span><span class="token punctuation">(</span><span class="token string">'google.com'</span><span class="token punctuation">);</span> <span class="token comment">// {}</span>
</pre></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="hextorgb">hexToRGB</h4><p>Converts a color code to a <code>rgb()</code> or <code>rgba()</code> string if alpha value is provided.</p><p>Use bitwise right-shift operator and mask bits with <code>&amp;</code> (and) operator to convert a hexadecimal color code (with or without prefixed with <code>#</code>) to a string with the RGB values. If it's 3-digit color code, first convert to 6-digit version. If an alpha value is provided alongside 6-digit hex, give <code>rgba()</code> string in return.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">hexToRGB</span> <span class="token operator">=</span> hex <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> alpha <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
    h <span class="token operator">=</span> hex<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span>hex<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">'#'</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token number">1</span> <span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">);</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>h<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">3</span><span class="token punctuation">)</span> h <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token operator">...</span>h<span class="token punctuation">].</span><span class="token function">map</span><span class="token punctuation">(</span>x <span class="token operator">=></span> x <span class="token operator">+</span> x<span class="token punctuation">).</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">);</span>
  <span class="token keyword">else if</span> <span class="token punctuation">(</span>h<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">8</span><span class="token punctuation">)</span> alpha <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  h <span class="token operator">=</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>h<span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">);</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>
    <span class="token string">'rgb'</span> <span class="token operator">+</span>
    <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token string">'a'</span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">+</span>
    <span class="token string">'('</span> <span class="token operator">+</span>
    <span class="token punctuation">(</span>h <span class="token operator">>>></span> <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token number">24</span> <span class="token punctuation">:</span> <span class="token number">16</span><span class="token punctuation">))</span> <span class="token operator">+</span>
    <span class="token string">', '</span> <span class="token operator">+</span>
    <span class="token punctuation">((</span>h <span class="token operator">&amp;</span> <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token number">0x00ff0000</span> <span class="token punctuation">:</span> <span class="token number">0x00ff00</span><span class="token punctuation">))</span> <span class="token operator">>>></span> <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token number">16</span> <span class="token punctuation">:</span> <span class="token number">8</span><span class="token punctuation">))</span> <span class="token operator">+</span>
    <span class="token string">', '</span> <span class="token operator">+</span>
    <span class="token punctuation">((</span>h <span class="token operator">&amp;</span> <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token number">0x0000ff00</span> <span class="token punctuation">:</span> <span class="token number">0x0000ff</span><span class="token punctuation">))</span> <span class="token operator">>>></span> <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token number">8</span> <span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">))</span> <span class="token operator">+</span>
    <span class="token punctuation">(</span>alpha <span class="token operator">?</span> <span class="token template-string"><span class="token string">`, </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>h <span class="token operator">&amp;</span> <span class="token number">0x000000ff</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">`</span></span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">+</span>
    <span class="token string">')'</span>
  <span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">hexToRGB</span><span class="token punctuation">(</span><span class="token string">'#27ae60ff'</span><span class="token punctuation">);</span> <span class="token comment">// 'rgba(39, 174, 96, 255)'</span>
<span class="token function">hexToRGB</span><span class="token punctuation">(</span><span class="token string">'27ae60'</span><span class="token punctuation">);</span> <span class="token comment">// 'rgb(39, 174, 96)'</span>
<span class="token function">hexToRGB</span><span class="token punctuation">(</span><span class="token string">'#fff'</span><span class="token punctuation">);</span> <span class="token comment">// 'rgb(255, 255, 255)'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="httpget">httpGet</h4><p>Makes a <code>GET</code> request to the passed URL.</p><p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest"><code>XMLHttpRequest</code></a> web api to make a <code>get</code> request to the given <code>url</code>. Handle the <code>onload</code> event, by calling the given <code>callback</code> the <code>responseText</code>. Handle the <code>onerror</code> event, by running the provided <code>err</code> function. Omit the third argument, <code>err</code>, to log errors to the console's <code>error</code> stream by default.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpGet</span> <span class="token operator">=</span> <span class="token punctuation">(</span>url<span class="token punctuation">,</span> callback<span class="token punctuation">,</span> err <span class="token operator">=</span> console<span class="token punctuation">.</span>error<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> request <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">XMLHttpRequest</span><span class="token punctuation">();</span>
  request<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token string">'GET'</span><span class="token punctuation">,</span> url<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">callback</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>responseText<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onerror</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">err</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">();
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">httpGet</span><span class="token punctuation">(</span>
  <span class="token string">'https://jsonplaceholder.typicode.com/posts/1'</span><span class="token punctuation">,</span>
  console<span class="token punctuation">.</span>log
<span class="token punctuation">);</span> <span class="token comment">/*
Logs: {
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
*/</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="httppost">httpPost</h4><p>Makes a <code>POST</code> request to the passed URL.</p><p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest"><code>XMLHttpRequest</code></a> web api to make a <code>post</code> request to the given <code>url</code>. Set the value of an <code>HTTP</code> request header with <code>setRequestHeader</code> method. Handle the <code>onload</code> event, by calling the given <code>callback</code> the <code>responseText</code>. Handle the <code>onerror</code> event, by running the provided <code>err</code> function. Omit the third argument, <code>data</code>, to send no data to the provided <code>url</code>. Omit the fourth argument, <code>err</code>, to log errors to the console's <code>error</code> stream by default.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">httpPost</span> <span class="token operator">=</span> <span class="token punctuation">(</span>url<span class="token punctuation">,</span> data<span class="token punctuation">,</span> callback<span class="token punctuation">,</span> err <span class="token operator">=</span> console<span class="token punctuation">.</span>error<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> request <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">XMLHttpRequest</span><span class="token punctuation">();</span>
  request<span class="token punctuation">.</span><span class="token function">open</span><span class="token punctuation">(</span><span class="token string">'POST'</span><span class="token punctuation">,</span> url<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">setRequestHeader</span><span class="token punctuation">(</span><span class="token string">'Content-type'</span><span class="token punctuation">,</span> <span class="token string">'application/json; charset=utf-8'</span><span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onload</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">callback</span><span class="token punctuation">(</span>request<span class="token punctuation">.</span>responseText<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function-variable function">onerror</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token function">err</span><span class="token punctuation">(</span>request<span class="token punctuation">);</span>
  request<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>data<span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> newPost <span class="token operator">=</span> <span class="token punctuation">{</span>
  userId<span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
  id<span class="token punctuation">:</span> <span class="token number">1337</span><span class="token punctuation">,</span>
  title<span class="token punctuation">:</span> <span class="token string">'Foo'</span><span class="token punctuation">,</span>
  body<span class="token punctuation">:</span> <span class="token string">'bar bar bar'</span>
<span class="token punctuation">};</span>
<span class="token keyword">const</span> data <span class="token operator">=</span> <span class="token constant">JSON</span><span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>newPost<span class="token punctuation">);</span>
<span class="token function">httpPost</span><span class="token punctuation">(</span>
  <span class="token string">'https://jsonplaceholder.typicode.com/posts'</span><span class="token punctuation">,</span>
  data<span class="token punctuation">,</span>
  console<span class="token punctuation">.</span>log
<span class="token punctuation">);</span> <span class="token comment">/*
Logs: {
  "userId": 1,
  "id": 1337,
  "title": "Foo",
  "body": "bar bar bar"
}
*/</span>
<span class="token function">httpPost</span><span class="token punctuation">(</span>
  <span class="token string">'https://jsonplaceholder.typicode.com/posts'</span><span class="token punctuation">,</span>
  <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token comment">// does not send a body</span>
  console<span class="token punctuation">.</span>log
<span class="token punctuation">);</span> <span class="token comment">/*
Logs: {
  "id": 101
}
*/</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="isbrowser">isBrowser</h4><p>Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.</p><p>Use <code>Array.prototype.includes()</code> on the <code>typeof</code> values of both <code>window</code> and <code>document</code> (globals usually only available in a browser environment unless they were explicitly defined), which will return <code>true</code> if one of them is <code>undefined</code>. <code>typeof</code> allows globals to be checked for existence without throwing a <code>ReferenceError</code>. If both of them are not <code>undefined</code>, then the current environment is assumed to be a browser.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">isBrowser</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=> !</span><span class="token punctuation">[</span><span class="token keyword">typeof</span> window<span class="token punctuation">,</span> <span class="token keyword">typeof</span> document<span class="token punctuation">].</span><span class="token function">includes</span><span class="token punctuation">(</span><span class="token string">'undefined'</span><span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">isBrowser</span><span class="token punctuation">();</span> <span class="token comment">// true (browser)</span>
<span class="token function">isBrowser</span><span class="token punctuation">();</span> <span class="token comment">// false (Node)</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="mostperformant">mostPerformant</h4><p>Returns the index of the function in an array of functions which executed the fastest.</p><p>Use <code>Array.prototype.map()</code> to generate an array where each value is the total time taken to execute the function after <code>iterations</code> times. Use the difference in <code>performance.now()</code> values before and after to get the total time in milliseconds to a high degree of accuracy. Use <code>Math.min()</code> to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function. Omit the second argument, <code>iterations</code>, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">mostPerformant</span> <span class="token operator">=</span> <span class="token punctuation">(</span>fns<span class="token punctuation">,</span> iterations <span class="token operator">=</span> <span class="token number">10000</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> times <span class="token operator">=</span> fns<span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>fn <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> before <span class="token operator">=</span> performance<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">();</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> iterations<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token function">fn</span><span class="token punctuation">();</span>
    <span class="token keyword">return</span> performance<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">()</span> <span class="token operator">-</span> before<span class="token punctuation">;
  });</span>
  <span class="token keyword">return</span> times<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span><span class="token operator">...</span>times<span class="token punctuation">));
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">mostPerformant</span><span class="token punctuation">([
  ()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token comment">// Loops through the entire array before returning `false`</span>
    <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">,</span> <span class="token string">'10'</span><span class="token punctuation">].</span><span class="token function">every</span><span class="token punctuation">(</span>el <span class="token operator">=></span> <span class="token keyword">typeof</span> el <span class="token operator">===</span> <span class="token string">'number'</span><span class="token punctuation">);
  },
  ()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token comment">// Only needs to reach index `1` before returning false</span>
    <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token string">'2'</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">].</span><span class="token function">every</span><span class="token punctuation">(</span>el <span class="token operator">=></span> <span class="token keyword">typeof</span> el <span class="token operator">===</span> <span class="token string">'number'</span><span class="token punctuation">);
  }
]);</span> <span class="token comment">// 1</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="ntharg">nthArg</h4><p>Creates a function that gets the argument at index <code>n</code>. If <code>n</code> is negative, the nth argument from the end is returned.</p><p>Use <code>Array.prototype.slice()</code> to get the desired argument at index <code>n</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">nthArg</span> <span class="token operator">=</span> n <span class="token operator">=></span> <span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span> <span class="token operator">=></span> args<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span>n<span class="token punctuation">)[</span><span class="token number">0</span><span class="token punctuation">];</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token keyword">const</span> third <span class="token operator">=</span> <span class="token function">nthArg</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">);</span>
<span class="token function">third</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">);</span> <span class="token comment">// 3</span>
<span class="token function">third</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">);</span> <span class="token comment">// undefined</span>
<span class="token keyword">const</span> last <span class="token operator">=</span> <span class="token function">nthArg</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">);</span>
<span class="token function">last</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">);</span> <span class="token comment">// 5</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="parsecookie">parseCookie</h4><p>Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.</p><p>Use <code>String.prototype.split(';')</code> to separate key-value pairs from each other. Use <code>Array.prototype.map()</code> and <code>String.prototype.split('=')</code> to separate keys from values in each pair. Use <code>Array.prototype.reduce()</code> and <code>decodeURIComponent()</code> to create an object with all key-value pairs.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">parseCookie</span> <span class="token operator">=</span> str <span class="token operator">=></span>
  str
    <span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">';'</span><span class="token punctuation">)
    .</span><span class="token function">map</span><span class="token punctuation">(</span>v <span class="token operator">=></span> v<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">'='</span><span class="token punctuation">))
    .</span><span class="token function">reduce</span><span class="token punctuation">((</span>acc<span class="token punctuation">,</span> v<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
      acc<span class="token punctuation">[</span><span class="token function">decodeURIComponent</span><span class="token punctuation">(</span>v<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">].</span><span class="token function">trim</span><span class="token punctuation">())]</span> <span class="token operator">=</span> <span class="token function">decodeURIComponent</span><span class="token punctuation">(</span>v<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">].</span><span class="token function">trim</span><span class="token punctuation">());</span>
      <span class="token keyword">return</span> acc<span class="token punctuation">;
    }, {});</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">parseCookie</span><span class="token punctuation">(</span><span class="token string">'foo=bar; equation=E%3Dmc%5E2'</span><span class="token punctuation">);</span> <span class="token comment">// { foo: 'bar', equation: 'E=mc^2' }</span>
</pre></div><div class="card code-card"><div class="section card-content"><h4><a href="https://frontendmasters.com/courses/js-fundamentals-functional-v2/" target="_blank" rel="noopener noreferrer">Recommended Resource - JavaScript: From Fundamentals to Functional JS</a></h4><p>Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.</p></div></div><div class="card code-card"><div class="corner advanced"></div><div class="section card-content"><h4 id="prettybytes">prettyBytes</h4><p>Converts a number in bytes to a human-readable string.</p><p>Use an array dictionary of units to be accessed based on the exponent. Use <code>Number.toPrecision()</code> to truncate the number to a certain number of digits. Return the prettified string by building it up, taking into account the supplied options and whether it is negative or not. Omit the second argument, <code>precision</code>, to use a default precision of <code>3</code> digits. Omit the third argument, <code>addSpace</code>, to add space between the number and unit by default.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">prettyBytes</span> <span class="token operator">=</span> <span class="token punctuation">(</span>num<span class="token punctuation">,</span> precision <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">,</span> addSpace <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> <span class="token constant">UNITS</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'B'</span><span class="token punctuation">,</span> <span class="token string">'KB'</span><span class="token punctuation">,</span> <span class="token string">'MB'</span><span class="token punctuation">,</span> <span class="token string">'GB'</span><span class="token punctuation">,</span> <span class="token string">'TB'</span><span class="token punctuation">,</span> <span class="token string">'PB'</span><span class="token punctuation">,</span> <span class="token string">'EB'</span><span class="token punctuation">,</span> <span class="token string">'ZB'</span><span class="token punctuation">,</span> <span class="token string">'YB'</span><span class="token punctuation">];</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">abs</span><span class="token punctuation">(</span>num<span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token keyword">return</span> num <span class="token operator">+</span> <span class="token punctuation">(</span>addSpace <span class="token operator">?</span> <span class="token string">' '</span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token constant">UNITS</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">];</span>
  <span class="token keyword">const</span> exponent <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">min</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">log10</span><span class="token punctuation">(</span>num <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">? -</span>num <span class="token punctuation">:</span> num<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">3</span><span class="token punctuation">),</span> <span class="token constant">UNITS</span><span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">);</span>
  <span class="token keyword">const</span> n <span class="token operator">=</span> <span class="token function">Number</span><span class="token punctuation">(((</span>num <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">? -</span>num <span class="token punctuation">:</span> num<span class="token punctuation">)</span> <span class="token operator">/</span> <span class="token number">1000</span> <span class="token operator">**</span> exponent<span class="token punctuation">).</span><span class="token function">toPrecision</span><span class="token punctuation">(</span>precision<span class="token punctuation">));</span>
  <span class="token keyword">return</span> <span class="token punctuation">(</span>num <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">?</span> <span class="token string">'-'</span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">+</span> n <span class="token operator">+</span> <span class="token punctuation">(</span>addSpace <span class="token operator">?</span> <span class="token string">' '</span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token constant">UNITS</span><span class="token punctuation">[</span>exponent<span class="token punctuation">];
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">prettyBytes</span><span class="token punctuation">(</span><span class="token number">1000</span><span class="token punctuation">);</span> <span class="token comment">// "1 KB"</span>
<span class="token function">prettyBytes</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">27145424323.5821</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">);</span> <span class="token comment">// "-27.145 GB"</span>
<span class="token function">prettyBytes</span><span class="token punctuation">(</span><span class="token number">123456789</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token boolean">false</span><span class="token punctuation">);</span> <span class="token comment">// "123MB"</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="randomhexcolorcode">randomHexColorCode</h4><p>Generates a random hexadecimal color code.</p><p>Use <code>Math.random</code> to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using <code>toString(16)</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">randomHexColorCode</span> <span class="token operator">=</span> <span class="token punctuation">()</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> n <span class="token operator">=</span> <span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">()</span> <span class="token operator">*</span> <span class="token number">0xfffff</span> <span class="token operator">*</span> <span class="token number">1000000</span><span class="token punctuation">).</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">);</span>
  <span class="token keyword">return</span> <span class="token string">'#'</span> <span class="token operator">+</span> n<span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">);
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">randomHexColorCode</span><span class="token punctuation">();</span> <span class="token comment">// "#e34155"</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="rgbtohex">RGBToHex</h4><p>Converts the values of RGB components to a color code.</p><p>Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (<code>&lt;&lt;</code>) and <code>toString(16)</code>, then <code>String.padStart(6,'0')</code> to get a 6-digit hexadecimal value.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">RGBToHex</span> <span class="token operator">=</span> <span class="token punctuation">(</span>r<span class="token punctuation">,</span> g<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">((</span>r <span class="token operator">&lt;&lt;</span> <span class="token number">16</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token punctuation">(</span>g <span class="token operator">&lt;&lt;</span> <span class="token number">8</span><span class="token punctuation">)</span> <span class="token operator">+</span> b<span class="token punctuation">).</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token number">16</span><span class="token punctuation">).</span><span class="token function">padStart</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> <span class="token string">'0'</span><span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">RGBToHex</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">,</span> <span class="token number">165</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">);</span> <span class="token comment">// 'ffa501'</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="serializecookie">serializeCookie</h4><p>Serialize a cookie name-value pair into a Set-Cookie header string.</p><p>Use template literals and <code>encodeURIComponent()</code> to create the appropriate string.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">serializeCookie</span> <span class="token operator">=</span> <span class="token punctuation">(</span>name<span class="token punctuation">,</span> val<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token template-string"><span class="token string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token function">encodeURIComponent</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">=</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token function">encodeURIComponent</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">`</span></span><span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">serializeCookie</span><span class="token punctuation">(</span><span class="token string">'foo'</span><span class="token punctuation">,</span> <span class="token string">'bar'</span><span class="token punctuation">);</span> <span class="token comment">// 'foo=bar'</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="timetaken">timeTaken</h4><p>Measures the time taken by a function to execute.</p><p>Use <code>console.time()</code> and <code>console.timeEnd()</code> to measure the difference between the start and end times to determine how long the callback took to execute.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">timeTaken</span> <span class="token operator">=</span> callback <span class="token operator">=></span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">time</span><span class="token punctuation">(</span><span class="token string">'timeTaken'</span><span class="token punctuation">);</span>
  <span class="token keyword">const</span> r <span class="token operator">=</span> <span class="token function">callback</span><span class="token punctuation">();</span>
  console<span class="token punctuation">.</span><span class="token function">timeEnd</span><span class="token punctuation">(</span><span class="token string">'timeTaken'</span><span class="token punctuation">);</span>
  <span class="token keyword">return</span> r<span class="token punctuation">;
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">timeTaken</span><span class="token punctuation">(()</span> <span class="token operator">=></span> Math<span class="token punctuation">.</span><span class="token function">pow</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">));</span> <span class="token comment">// 1024, (logged): timeTaken: 0.02099609375ms</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="tocurrency">toCurrency</h4><p>Take a number and return specified currency formatting.</p><p>Use <code>Intl.NumberFormat</code> to enable country / currency sensitive formatting.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">toCurrency</span> <span class="token operator">=</span> <span class="token punctuation">(</span>n<span class="token punctuation">,</span> curr<span class="token punctuation">,</span> LanguageFormat <span class="token operator">=</span> undefined<span class="token punctuation">)</span> <span class="token operator">=></span>
  Intl<span class="token punctuation">.</span><span class="token function">NumberFormat</span><span class="token punctuation">(</span>LanguageFormat<span class="token punctuation">, {</span> style<span class="token punctuation">:</span> <span class="token string">'currency'</span><span class="token punctuation">,</span> currency<span class="token punctuation">:</span> curr <span class="token punctuation">}).</span><span class="token function">format</span><span class="token punctuation">(</span>n<span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toCurrency</span><span class="token punctuation">(</span><span class="token number">123456.789</span><span class="token punctuation">,</span> <span class="token string">'EUR'</span><span class="token punctuation">);</span> <span class="token comment">// €123,456.79  | currency: Euro | currencyLangFormat: Local</span>
<span class="token function">toCurrency</span><span class="token punctuation">(</span><span class="token number">123456.789</span><span class="token punctuation">,</span> <span class="token string">'USD'</span><span class="token punctuation">,</span> <span class="token string">'en-us'</span><span class="token punctuation">);</span> <span class="token comment">// $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)</span>
<span class="token function">toCurrency</span><span class="token punctuation">(</span><span class="token number">123456.789</span><span class="token punctuation">,</span> <span class="token string">'USD'</span><span class="token punctuation">,</span> <span class="token string">'fa'</span><span class="token punctuation">);</span> <span class="token comment">// ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi</span>
<span class="token function">toCurrency</span><span class="token punctuation">(</span><span class="token number">322342436423.2435</span><span class="token punctuation">,</span> <span class="token string">'JPY'</span><span class="token punctuation">);</span> <span class="token comment">// ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local</span>
<span class="token function">toCurrency</span><span class="token punctuation">(</span><span class="token number">322342436423.2435</span><span class="token punctuation">,</span> <span class="token string">'JPY'</span><span class="token punctuation">,</span> <span class="token string">'fi'</span><span class="token punctuation">);</span> <span class="token comment">// 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish</span>
</pre></div><div class="card code-card"><div class="corner beginner"></div><div class="section card-content"><h4 id="todecimalmark">toDecimalMark</h4><p>Use <code>toLocaleString()</code> to convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form. It makes a comma separated string from a number.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">toDecimalMark</span> <span class="token operator">=</span> num <span class="token operator">=></span> num<span class="token punctuation">.</span><span class="token function">toLocaleString</span><span class="token punctuation">(</span><span class="token string">'en-US'</span><span class="token punctuation">);</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toDecimalMark</span><span class="token punctuation">(</span><span class="token number">12305030388.9087</span><span class="token punctuation">);</span> <span class="token comment">// "12,305,030,388.909"</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="toordinalsuffix">toOrdinalSuffix</h4><p>Adds an ordinal suffix to a number.</p><p>Use the modulo operator (<code>%</code>) to find values of single and tens digits. Find which ordinal pattern digits match. If digit is found in teens pattern, use teens ordinal.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">toOrdinalSuffix</span> <span class="token operator">=</span> num <span class="token operator">=></span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> int <span class="token operator">=</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>num<span class="token punctuation">),</span>
    digits <span class="token operator">=</span> <span class="token punctuation">[</span>int <span class="token operator">%</span> <span class="token number">10</span><span class="token punctuation">,</span> int <span class="token operator">%</span> <span class="token number">100</span><span class="token punctuation">],</span>
    ordinals <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'st'</span><span class="token punctuation">,</span> <span class="token string">'nd'</span><span class="token punctuation">,</span> <span class="token string">'rd'</span><span class="token punctuation">,</span> <span class="token string">'th'</span><span class="token punctuation">],</span>
    oPattern <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">],</span>
    tPattern <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">11</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">];</span>
  <span class="token keyword">return</span> oPattern<span class="token punctuation">.</span><span class="token function">includes</span><span class="token punctuation">(</span>digits<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">])</span> <span class="token operator">&amp;&amp; !</span>tPattern<span class="token punctuation">.</span><span class="token function">includes</span><span class="token punctuation">(</span>digits<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">])</span>
    <span class="token operator">?</span> int <span class="token operator">+</span> ordinals<span class="token punctuation">[</span>digits<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]
    :</span> int <span class="token operator">+</span> ordinals<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">];
};</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">toOrdinalSuffix</span><span class="token punctuation">(</span><span class="token string">'123'</span><span class="token punctuation">);</span> <span class="token comment">// "123rd"</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="validatenumber">validateNumber</h4><p>Returns <code>true</code> if the given value is a number, <code>false</code> otherwise.</p><p>Use <code>!isNaN()</code> in combination with <code>parseFloat()</code> to check if the argument is a number. Use <code>isFinite()</code> to check if the number is finite. Use <code>Number()</code> to check if the coercion holds.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">validateNumber</span> <span class="token operator">=</span> n <span class="token operator">=> !</span><span class="token function">isNaN</span><span class="token punctuation">(</span><span class="token function">parseFloat</span><span class="token punctuation">(</span>n<span class="token punctuation">))</span> <span class="token operator">&amp;&amp;</span> <span class="token function">isFinite</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token function">Number</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span> <span class="token operator">==</span> n<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">validateNumber</span><span class="token punctuation">(</span><span class="token string">'10'</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
</pre></div><div class="card code-card"><div class="corner intermediate"></div><div class="section card-content"><h4 id="yesno">yesNo</h4><p>Returns <code>true</code> if the string is <code>y</code>/<code>yes</code> or <code>false</code> if the string is <code>n</code>/<code>no</code>.</p><p>Use <code>RegExp.test()</code> to check if the string evaluates to <code>y/yes</code> or <code>n/no</code>. Omit the second argument, <code>def</code> to set the default answer as <code>no</code>.</p></div><div class="copy-button-container"><button class="copy-button" aria-label="Copy to clipboard"></button></div><pre class="section card-code language-js"><span class="token keyword">const</span> <span class="token function-variable function">yesNo</span> <span class="token operator">=</span> <span class="token punctuation">(</span>val<span class="token punctuation">,</span> def <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">)</span> <span class="token operator">=></span>
  <span class="token regex">/^(y|yes)$/i</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token boolean">true</span> <span class="token punctuation">:</span> <span class="token regex">/^(n|no)$/i</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token boolean">false</span> <span class="token punctuation">:</span> def<span class="token punctuation">;</span>
</pre><label class="collapse">examples</label><pre class="section card-examples language-js"><span class="token function">yesNo</span><span class="token punctuation">(</span><span class="token string">'Y'</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
<span class="token function">yesNo</span><span class="token punctuation">(</span><span class="token string">'yes'</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
<span class="token function">yesNo</span><span class="token punctuation">(</span><span class="token string">'No'</span><span class="token punctuation">);</span> <span class="token comment">// false</span>
<span class="token function">yesNo</span><span class="token punctuation">(</span><span class="token string">'Foo'</span><span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">);</span> <span class="token comment">// true</span>
</pre></div></main><footer class="col-full-width container"><div class="col-centered"><p style="display:inline-block"><strong>30 seconds of code</strong> is licensed under the <a href="https://github.com/30-seconds/30-seconds-of-code/blob/master/LICENSE">CC0-1.0</a> license.<br>Logos made by <a href="https://github.com/Chalarangelo">Angelos Chalaris</a> and ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> are licensed under the <a href="https://opensource.org/licenses/MIT">MIT</a> license.<br>Sponsored by <img src="https://30secondsofcode.org/sponsors/DO_Logo_icon_blue.svg" style="vertical-align:sub;padding-right:2px;padding-left:2px" width="20px" height="20px"><a href="https://www.digitalocean.com" alt="DigitalOcean"><span style="color:#0080ff">DigitalOcean</span></a>.</p><br/><p style="display:inline-block"><a href="./about">About</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./contributing">Contributing</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./archive">Archive</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="./glossary">Glossary</a></p></div></footer><a class="scroll-to-top" href="#top"></a></div></body></html>